import { Hono } from "hono";
import { cors } from "hono/cors";
import { auth } from "./lib/auth";
import { logger } from "./lib/logger";
import orgs from "./routes/orgs";
import reports from "./routes/reports";
import tests from "./routes/tests";

const app = new Hono<{
  Variables: {
    user: typeof auth.$Infer.Session.user | null;
    session: typeof auth.$Infer.Session.session | null;
  };
}>();

app.use(
  "/*",
  cors({
    origin: process.env.CORS_ORIGIN || "",
    allowHeaders: ["Content-Type", "Authorization"],
    allowMethods: ["POST", "GET", "OPTIONS"],
    exposeHeaders: ["Content-Length"],
    maxAge: 60 * 60 * 7 * 24,
    credentials: true,
  }),
);

app.use("*", async (c, next) => {
  const session = await auth.api.getSession({ headers: c.req.raw.headers });

  if (!session) {
    c.set("user", null);
    c.set("session", null);
    return next();
  }

  c.set("user", session.user);
  c.set("session", session.session);
  return next();
});

app.use("*", async (c, next) => {
  const start = Date.now();
  await next();
  const ms = Date.now() - start;
  logger.info(`[${c.req.method}] ${c.req.path} - ${c.res.status} - ${ms}ms`);
});

app.on(["POST", "GET"], "/api/auth/*", (c) => auth.handler(c.req.raw));

const routes = app.route("/orgs", orgs).route("/reports", reports).route("/tests", tests);

export default app;
export type AppType = typeof routes;
